<?php
declare (strict_types=1);

namespace app\backend\controller\v4;

use app\backend\validate\LoginValidate;
use app\common\models\ApiMember as ApiMemberModel;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Request;

class ApiMember extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //搜索
        $where1 = input('nickname');
        $where2 = input('account');

        $page = input('page/d', 1);
        $pageSize = input('pageSize/d', 10);
        $model = new ApiMemberModel();
        $data = $model
            ->where(function ($query) use ($where1, $where2) {
                if ($where1) {
                    $query->where('nickname', 'like', '%' . $where1 . '%');
                }
                if ($where2) {
                    $query->where('account', 'like', '%' . $where2 . '%');
                }
            })
            ->with('backend')
            ->order('id','desc')
            ->page($page, $pageSize)
            ->select()->toArray();
        $count = ApiMemberModel::count();
        $maxpage = ceil($count / $pageSize);
        foreach ($data as &$v) {
//            dd($v);
            $v['backend_member_name'] = '无';
            if (!empty($v['backend'])){
                $v['backend_member_name'] = $v['backend']['username'];
            }
//            unset($v->backend);

            if ($v['past_time'] <= date('Y-m-d H:i:s', time())) {
                //dd($v['past_time']);
                $v['status'] = -1;
            }
            $model->where('id', $v['id'])->update(['status' => $v['status']]);
        }
        return sucessMsg(200, '获取成功', ['data' => $data, 'total' => $count, 'page' => $maxpage]);
    }

    /***
     * 清除缓存
     */
    public function clearCache()
    {
        Cache::clear();
        return sucessMsg(200, '请求成功');
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(\think\Request $request)
    {
        $postData = input('post.');
        try {
            //  验证参数
            validate(LoginValidate::class)->scene('save')->check($postData);
            $user = new ApiMemberModel();
            $memberInfo = $user->fetchInfoByWhere(['account' => $postData['account']], 'id,account');
            if (!empty($memberInfo)) {
                return errMsg(422, '账号已存在！');
            }
            $postData['salt'] = getRandStr(6);
            $postData['password_hash'] = makePassword($postData['password'], $postData['salt']);
            if ($postData['past_time'] <= date('Y-m-d H:i:s', time())) {
                return errMsg(400, '请输入正确的期限！');
            }
            // 获取表单上传文件
            $file = request()->file('avatar');
            if (!empty($file)) {
                // 上传
                $savename = \think\facade\Filesystem::disk('public')->putFile('/uploads', $file);
                $postData['avatar'] = $savename;
            }
            if ($user->save($postData)) {
                return sucessMsg(200, '添加成功');
            }
            return errMsg(422, '添加失败');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @return \think\Response
     */
    public function edit()
    {
        //
        $model = new ApiMemberModel();
        $id = input('get.id/d');
        if (empty($id)) {
            return errMsg(422, 'id不能为空');
        }
        $data = $model->where('id', $id)->find();
        if (empty($data))
            return errMsg(422, '无效id');
        return sucessMsg(200, '获取成功！', $data);
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $postData = input('post.');
        try {
            //  验证参数
            validate(LoginValidate::class)->scene('update')->check($postData);
            $model = new ApiMemberModel();
            if (!empty($postData['password'])){
                $postData['salt'] = getRandStr(6);
                $postData['password_hash'] = makePassword($postData['password'], $postData['salt']);
            }
            unset($postData['password']);
            // 获取表单上传文件
            $file = request()->file('avatar');
            if (!empty($file)) {
                // 上传
                $savename = \think\facade\Filesystem::disk('public')->putFile('/uploads', $file);
                $postData['avatar'] = $savename;
            }
            $cate = $model->where('id', $postData['id'])->find();
            if ($cate->save($postData))
                return sucessMsg(200, '修改成功');
            return sucessMsg(422, '修改失败');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 删除指定资源
     *
     * @return \think\Response
     */
    public function delete()
    {
        //
        $model = new ApiMemberModel();
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(422, 'id不能为空');
        }
        $data = $model->where('id', $id)->find();
        if (empty($data))
            return errMsg(422, '无效id');
        if (ApiMemberModel::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(422, '删除失败');
    }

    public function membercount()
    {
        $model = new ApiMemberModel();
        $count = count($model->select());
        return sucessMsg(200, '获取成功', $count);
    }

}